﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier_Service;
using Cashier.pos;
using Cashier.utils;
using Cashier_Utils;
using System.Collections;
using Cashier_Model;

namespace Cashier.purchase
{
    public partial class RepurchaseAddForm : Form, IGoodsNorm
    {
        private MainForm mainform;
        private IReloadData iReloadData;
        private static RepurchaseAddForm repurchaseAddForm;
        private BillPurchaseGoodsService purchaseGoodsService;
        private BillRepurchaseService repurchaseService;
        private long goodsID;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        private RepurchaseAddForm(MainForm mainform, IReloadData iReloadData)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.iReloadData = iReloadData;
            this.purchaseGoodsService = new BillPurchaseGoodsService();
            this.repurchaseService = new BillRepurchaseService();
            this.GenerateDataGridViewColumns();

            Button[] buttons = { button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
        }

        /// <summary>
        /// 获取窗体实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="iReloadData"></param>
        /// <returns></returns>
        public static RepurchaseAddForm GetRepurchaseAddForm(MainForm mainform, IReloadData iReloadData)
        {
            if (repurchaseAddForm == null)
                repurchaseAddForm = new RepurchaseAddForm(mainform, iReloadData);
            return repurchaseAddForm;
        }

        #region 功能方法实现

        /// <summary>
        /// 生成DataGridView列
        /// </summary>
        private void GenerateDataGridViewColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("barcode", "商品条码", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));            
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_name", "名称", true, 10, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("category_name", "分类", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_norm", "规格", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_cost", "进货单价", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount", "折扣率", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_disc", "折后单价", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "采购数量", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_total", "采购金额", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("renumbers", "退货数量", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("owe_total", "退货金额", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("supplier_name", "供货商", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 9, ActKey.LEFT, ActKey.LEFT, true, false));
        }

        /// <summary>
        /// 商品信息控件赋值
        /// </summary>
        /// <param name="row"></param>
        private void InitialGoodsData(DataRow row)
        {
            if (row != null)
            {
                goodsID = row["goods_id"] != DBNull.Value ? (long)row["goods_id"] : 0;
                textbox_renumbers.Text = row["numbers"].ToString();
                textbox_oweTotal.Text = ((decimal)row["total"]).ToString("f2");
                label_goodsName.Text = row["goods_name"].ToString();
                label_categoryname.Text = row["category_name"].ToString();
                label_goodsNorm.Text = row["goods_norm"].ToString();
                label_supplierName.Text = row["supplier_name"].ToString();
                label_priceCost.Text = ((decimal)row["price_cost"]).ToString("f2");
                label_discount.Text = ((decimal)row["discount"]).ToString("f2");
                label_priceDisc.Text = ((decimal)row["price_disc"]).ToString("f2");
                label_goodsNumber.Text = row["numbers"].ToString();
                label_goodsAmount.Text = ((decimal)row["total"]).ToString("f2");
            }
        }

        /// <summary>
        /// 验证退货商品信息
        /// </summary>
        /// <returns></returns>
        private bool ValidateGoodsData()
        {
            bool pass = false;
            try
            {
                String renumbers = textbox_renumbers.Text.Trim();
                int numbers = Int32.Parse(renumbers);
                int buyNumbers = Int32.Parse(label_goodsNumber.Text);
                if (numbers <= buyNumbers)
                    pass = true;
                else
                {
                    pass = false;
                    MessageBox.Show("退货数量不能高于采购数量！");
                }

                decimal returnAmount = Decimal.Parse(textbox_oweTotal.Text.Trim());
                decimal goodsAmount = Decimal.Parse(label_goodsAmount.Text);
                if (returnAmount < 0)
                {
                    pass = false;
                    MessageBox.Show("退货商品金额不得为负数！");
                }
                else if (returnAmount > goodsAmount)
                {
                    pass = false;
                    MessageBox.Show("退货商品金额不得高出商品采购金额！");
                }
                else
                    pass = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return pass;
        }

        /// <summary>
        /// 添加退货商品
        /// </summary>
        private void AddReturnGoods()
        {
            if (this.ValidateGoodsData())
            {
                bool isExist = false;
                String barcode = textbox_barcode.Text.Trim();
                String goodsNorm = label_goodsNorm.Text;
                int numbers = Int32.Parse(textbox_renumbers.Text.Trim());
                int buyNumbers = Int32.Parse(label_goodsNumber.Text);
                if (this.dataGridView1.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in this.dataGridView1.Rows)
                    {
                        if (barcode.Equals(row.Cells["barcode"].Value.ToString()) &&
                            goodsNorm.Equals(row.Cells["goods_norm"].Value.ToString()))
                        {
                            isExist = true;
                            numbers = (int)row.Cells["renumbers"].Value + numbers;
                            if (numbers <= buyNumbers)
                            {
                                row.Cells["renumbers"].Value = numbers;
                                row.Cells["owe_total"].Value = Decimal.Parse(label_priceDisc.Text) * (int)row.Cells["renumbers"].Value;
                            }
                            else
                                MessageBox.Show("退货数量不能高于采购数量！");
                            break;
                        }
                    }
                }
                if (!isExist)
                {
                    int rowIndex = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[rowIndex].Cells["goods_id"].Value = this.goodsID;
                    this.dataGridView1.Rows[rowIndex].Cells["barcode"].Value = barcode;
                    this.dataGridView1.Rows[rowIndex].Cells["goods_name"].Value = label_goodsName.Text;
                    this.dataGridView1.Rows[rowIndex].Cells["category_name"].Value = label_categoryname.Text;
                    this.dataGridView1.Rows[rowIndex].Cells["goods_norm"].Value = goodsNorm;
                    this.dataGridView1.Rows[rowIndex].Cells["price_cost"].Value = Decimal.Parse(label_priceCost.Text);
                    this.dataGridView1.Rows[rowIndex].Cells["discount"].Value = Decimal.Parse(label_discount.Text);
                    this.dataGridView1.Rows[rowIndex].Cells["price_disc"].Value = Decimal.Parse(label_priceDisc.Text);
                    this.dataGridView1.Rows[rowIndex].Cells["numbers"].Value = buyNumbers;
                    this.dataGridView1.Rows[rowIndex].Cells["goods_total"].Value = Decimal.Parse(label_goodsAmount.Text);
                    this.dataGridView1.Rows[rowIndex].Cells["renumbers"].Value = numbers;
                    this.dataGridView1.Rows[rowIndex].Cells["owe_total"].Value = Decimal.Parse(textbox_oweTotal.Text.Trim());
                    this.dataGridView1.Rows[rowIndex].Cells["supplier_name"].Value = label_supplierName.Text;
                    this.dataGridView1.Rows[rowIndex].Cells["note"].Value = textbox_goodsnote.Text.Trim();
                }

                this.goodsID = 0;
                textbox_barcode.Text = String.Empty;
                textbox_renumbers.Text = "0";
                textbox_oweTotal.Text = "0.00";
                textbox_goodsnote.Text = String.Empty;
                label_goodsName.Text = String.Empty;
                label_categoryname.Text = String.Empty;
                label_goodsNorm.Text = String.Empty;
                label_supplierName.Text = String.Empty;
                label_priceCost.Text = "0.00";
                label_discount.Text = "1";
                label_priceDisc.Text = "0.00";
                label_goodsNumber.Text = "0";
                label_goodsAmount.Text = "0.00";

                this.RepurchaseAccount();
                textbox_barcode.Focus();
            }
        }

        /// <summary>
        /// 计算退货单
        /// </summary>
        private void RepurchaseAccount()
        {
            int renumbers = 0;
            decimal total = 0M;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                renumbers += (int)row.Cells["renumbers"].Value;
                total += (decimal)row.Cells["owe_total"].Value;
            }
            label_numbers.Text = renumbers.ToString();
            label_goodsTotal.Text = total.ToString("f2");
            textbox_repurchaseTotal.Text = total.ToString("f2");

            if (renumbers == 0)
            {
                textbox_fare.Text = "0.00";
                textbox_otherCost.Text = "0.00";
                textbox_returnCost.Text = "0.00";
                textbox_note.Text = String.Empty;
            }
        }

        /// <summary>
        /// 删除退货商品
        /// </summary>
        private void DeleteReturnGoods()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除所选商品吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
                    {
                        this.dataGridView1.Rows.Remove(row);
                    }

                    this.RepurchaseAccount();
                    textbox_barcode.Focus();
                }
            }
        }

        /// <summary>
        /// 保存退货单
        /// </summary>
        private void SaveRepurchase()
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                String repurchaseNO = ToolsUtil.GenerateRepurchaseNO();
                String purchaseNO = textbox_purchaseno.Text.Trim();
                int numbers = 0;
                decimal total = 0M;

                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String storeNo = mainform.Admin.StoreNo;
                String adminUsername = mainform.Admin.Username;
                String adminName = mainform.Admin.Name;
                ArrayList list = new ArrayList();
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    BillRepurchaseGoods goods = new BillRepurchaseGoods();
                    goods.EnterpriseNo = enterpriseNo;
                    goods.StoreNo = storeNo;
                    goods.RepurchaseNo = repurchaseNO;
                    goods.PurchaseNo = purchaseNO;
                    goods.SupplierName = row.Cells["supplier_name"].Value.ToString();
                    goods.GoodsId = (long)row.Cells["goods_id"].Value;
                    goods.Barcode = row.Cells["barcode"].Value.ToString();
                    goods.CategoryName = row.Cells["category_name"].Value.ToString();
                    goods.GoodsName = row.Cells["goods_name"].Value.ToString();
                    goods.GoodsNorm = row.Cells["goods_norm"].Value.ToString();
                    goods.PriceCost = (decimal)row.Cells["price_cost"].Value;
                    goods.Discount = (decimal)row.Cells["discount"].Value;
                    goods.PriceDisc = (decimal)row.Cells["price_disc"].Value;
                    goods.Numbers = Int32.Parse(row.Cells["numbers"].Value.ToString());
                    goods.GoodsTotal = (decimal)row.Cells["goods_total"].Value;
                    goods.Renumbers = Int32.Parse(row.Cells["renumbers"].Value.ToString());
                    goods.OweTotal = (decimal)row.Cells["owe_total"].Value;
                    goods.Note = row.Cells["note"].Value.ToString();
                    goods.AdminUsername = adminUsername;
                    goods.AdminName = adminName;
                    goods.Createtime = DateTime.Now;
                    list.Add(goods);
                    numbers += goods.Renumbers;
                    total += goods.OweTotal;
                }

                BillRepurchase billRepurchase = new BillRepurchase();
                billRepurchase.EnterpriseNo = enterpriseNo;
                billRepurchase.StoreNo = storeNo;
                billRepurchase.RepurchaseNo = repurchaseNO;
                billRepurchase.PurchaseNo = purchaseNO;
                billRepurchase.Numbers = numbers;
                billRepurchase.GoodsTotal = total;
                billRepurchase.RepurchaseTotal = Decimal.Parse(textbox_repurchaseTotal.Text.Trim());
                billRepurchase.Fare = Decimal.Parse(textbox_fare.Text.Trim());
                billRepurchase.OtherCost = Decimal.Parse(textbox_otherCost.Text.Trim());
                billRepurchase.CountTotal = billRepurchase.RepurchaseTotal + billRepurchase.Fare + billRepurchase.OtherCost;
                billRepurchase.ReturnCost = Decimal.Parse(textbox_returnCost.Text.Trim());
                billRepurchase.RepurchaseDate = DateTime.Now;
                billRepurchase.Note = textbox_note.Text.Trim();
                billRepurchase.IsRefund = false;
                billRepurchase.AdminUsername = adminUsername;
                billRepurchase.AdminName = adminName;
                billRepurchase.Createtime = DateTime.Now;

                long id = this.repurchaseService.InsertBillRepurchase(billRepurchase, list);
                if (id > 0)
                {
                    textbox_purchaseno.Text = String.Empty;
                    label_numbers.Text = "0";
                    label_goodsTotal.Text = "0.00";
                    textbox_repurchaseTotal.Text = "0.00";
                    textbox_fare.Text = "0.00";
                    textbox_otherCost.Text = "0.00";
                    textbox_returnCost.Text = "0.00";
                    textbox_note.Text = String.Empty;
                    this.dataGridView1.Rows.Clear();

                    DialogResult result = MessageBox.Show("保存成功，要继续新建吗？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.No)
                    {
                        this.Close();
                    }
                }
                else
                    MessageBox.Show("保存失败！");
            }
            else
                MessageBox.Show("没有任何商品！");
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 退货单号文本框键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_purchaseno_KeyPress(object sender, KeyPressEventArgs e)
        {
            String purchaseno = textbox_purchaseno.Text.Trim();
            if ((int)e.KeyChar == 13 && !String.IsNullOrEmpty(purchaseno))
            {
                textbox_barcode.Focus();
            }
        }

        /// <summary>
        /// 商品条码文本框键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_barcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            String purchaseno = textbox_purchaseno.Text.Trim();
            String barcode = textbox_barcode.Text.Trim();
            if((int)e.KeyChar==13 && !String.IsNullOrEmpty(barcode))
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String adminUsername = mainform.UsernameForQuery;
                DataTable dt = this.purchaseGoodsService.GetBillPurchaseGoodsTable(0, 0, adminUsername, string.Empty, purchaseno, barcode, 
                    adminUsername, null, null, null, "id");
                if (dt != null && dt.Rows.Count > 0)
                {
                    textbox_renumbers.Focus();
                    if (dt.Rows.Count > 1)
                    {
                        GoodsNormForm goodsNormForm = new GoodsNormForm(this, dt, "goods_norm", "goods_id");
                        goodsNormForm.ShowDialog();
                    }
                    else
                    {
                        this.InitialGoodsData(dt.Rows[0]);
                    }
                }
            }
        }

        /// <summary>
        /// 商品数量文本框键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textbox_renumbers_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                String renumbers = textbox_renumbers.Text.Trim();
                if ((int)e.KeyChar == 13 && !String.IsNullOrEmpty(renumbers))
                {
                    int numbers = Int32.Parse(renumbers);
                    int buyNumbers = Int32.Parse(label_goodsNumber.Text);
                    if (numbers <= buyNumbers)
                    {
                        decimal priceDisc = Decimal.Parse(label_priceDisc.Text);
                        textbox_oweTotal.Text = (priceDisc * numbers).ToString("f2");
                        textbox_oweTotal.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 新增退货商品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_addGoods_Click(object sender, EventArgs e)
        {
            this.AddReturnGoods();
        }

        /// <summary>
        /// 删除退货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_delete_Click(object sender, EventArgs e)
        {
            this.DeleteReturnGoods();
        }

        /// <summary>
        /// 保存采购退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            this.SaveRepurchase();
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepurchaseAddForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            int numbers = Int32.Parse(label_numbers.Text);
            if (numbers > 0)
            {
                DialogResult result = MessageBox.Show("尚未保存，确定要退出吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.No)
                    e.Cancel = true;
                else
                    repurchaseAddForm = null;
            }
            else
                repurchaseAddForm = null;
        }

        #endregion


        #region IGoodsNorm 成员

        void IGoodsNorm.SelectGoodsNorm(object param)
        {
            if (param != null)
            {
                DataRow row = (DataRow)param;
                this.InitialGoodsData(row);
            }
        }

        #endregion


        #region 重写事件

        /// <summary>
        /// 键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.Escape:
                    this.Close();
                    break;
                case Keys.F5:
                    this.SaveRepurchase();
                    break;
                case Keys.Add:
                    this.AddReturnGoods();
                    b = true;
                    break;
                case Keys.Oemplus:
                    this.AddReturnGoods();
                    b = true;
                    break;
                case Keys.Delete:
                    this.DeleteReturnGoods();
                    b = true;
                    break;
            }
            return b;
        }

        #endregion


    }
}
